import Canvas2DApplication from "../Canvas2DApplication";
import IDispatcher from "../interfaces/IDispatcher";
import ISpriteContainer from "../interfaces/ISpriteContainer";
import CanvasMouseEvent from "../events/CanvasMouseEvent";
import CanvasKeyBoardEvent from "../events/CanvasKeyBoardEvent";
import Sprite2DManager from "./Sprite2DManager";
import SpriteNodeManager from "./SpriteNodeManager";

export default class Sprite2DApplication extends Canvas2DApplication {
    // 声明一个受保护的类型为IDispatcher的成员变量
    // 下面所有的虚方法都委托调用IDispatcher相关的方法
    protected _dispatcher!: IDispatcher;
    // 一个方便的只读属性，返回ISpriteContainer容器接口
    // 可以通过该方法，和ISprite进行交互
    public get rootContainer(): ISpriteContainer {
        return this._dispatcher.container;
    }

    public constructor(canvas: HTMLCanvasElement, isHierarchical: boolean = true) {
        // 取消右键上下文菜单，这样就可以使用鼠标右键进行事件处理
        document.oncontextmenu = () => { return false; }
        super(canvas);
        if (isHierarchical === true) {
            this._dispatcher = new SpriteNodeManager(canvas.width, canvas.height);
        } else {
            this._dispatcher = new Sprite2DManager();
        }
    }

    public update(msec: number, diff: number): void {
        this._dispatcher.dispatchUpdate(msec, diff);
    }

    public render(): void {
        if (this.context2D) {
            // 每次都先将整个画布内容清空
            this.context2D.clearRect(0, 0, this.context2D.canvas.width, this.context2D.canvas.height);
            this._dispatcher.dispatchDraw(this.context2D);
        }
    }

    protected dispatchMouseDown(evt: CanvasMouseEvent): void {
        // 调用基类的同名方法
        super.dispatchMouseDown(evt);
        // 事件分发
        this._dispatcher.dispatchMouseEvent(evt);
    }

    protected dispatchMouseUp(evt: CanvasMouseEvent): void {
        super.dispatchMouseUp(evt);
        this._dispatcher.dispatchMouseEvent(evt);
    }
    protected dispatchMouseMove(evt: CanvasMouseEvent): void {
        super.dispatchMouseMove(evt);
        this._dispatcher.dispatchMouseEvent(evt);
    }
    protected dispatchMouseDrag(evt: CanvasMouseEvent): void {
        super.dispatchMouseDrag(evt);
        this._dispatcher.dispatchMouseEvent(evt);
    }

    protected dispatchKeyDown(evt: CanvasKeyBoardEvent): void {
        super.dispatchKeyDown(evt);
        this._dispatcher.dispatchKeyEvent(evt);
    }

    protected dispatchKeyUp(evt: CanvasKeyBoardEvent): void {
        super.dispatchKeyUp(evt);
        this._dispatcher.dispatchKeyEvent(evt);
    }

    protected dispatchKeyPress(evt: CanvasKeyBoardEvent): void {
        super.dispatchKeyPress(evt);
        this._dispatcher.dispatchKeyEvent(evt);
    }

}